package com.learn.netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatcher;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.internal.ChannelUtils;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @author zhongshitao
 * @date 2020/10/23 11:20 下午
 */
@Slf4j
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {


    private static ChannelGroup onlineUserGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 表示连接建立，一旦连接建立第一个被执行的方法
     * 将当前的channel加入到channelgroup
     * @param ctx
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        String msg = String.format("用户:%s 加入群聊\n", ctx.channel().remoteAddress());
        log.info("[客户端]-{}-{}-{}", LocalDateTime.now(), Thread.currentThread().getName(), msg);
        // 该方法会叫channelgroup中所有的channel遍历 并发送消息
        onlineUserGroup.writeAndFlush(msg);
        onlineUserGroup.add(ctx.channel());
    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelInactive()} to forward
     * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("[客户端]-{}-{}-{}", LocalDateTime.now(), Thread.currentThread().getName(), "下线了\n");

    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelActive()} to forward
     * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("[客户端]-{}-{}-{}", LocalDateTime.now(), Thread.currentThread().getName(), "上线了\n");
    }

    /**
     * Do nothing by default, sub-classes may override this method.
     *
     * @param ctx
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        String msg = String.format("用户:%s 离开了\n", ctx.channel().remoteAddress());
        log.info("[客户端]-{}-{}-{}", LocalDateTime.now(), Thread.currentThread().getName(), msg);
        // 该方法会叫channelgroup中所有的channel遍历 并发送消息
        onlineUserGroup.writeAndFlush(msg);
    }

    /**
     * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     * <p>
     * Is called for each message of type {@link I}.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("[客户端]-{}-{}-{}", LocalDateTime.now(), Thread.currentThread().getName(), msg);
        Channel channel = ctx.channel();
        onlineUserGroup.forEach(ch1 -> {
            if (ch1 != channel) {
                ch1.writeAndFlush(msg);
            }
        });
    }
}
